//
//  TKYAddSafetyController.m
//  StationHouseHelper
//
//  Created by apple on 2018/6/28.
//  Copyright © 2018年 铁科院. All rights reserved.
//

#import "TKYAddSafetyController.h"
#import "TKYAddSafetyCell.h"
#import "TKYSafetyDescribeCell.h"
#import "TKYSafetyImageOrVideoCell.h"
#import "TKYSelectedFileController.h"
#import "TKYSafetyMaterialCell.h"
#import "TKYSelectedPersonController.h"
#import "BRPickerView.h"
#import "TKYFindTreeController.h"
#import "TKYQuestionTypeController.h"
#import "TKYQuestionLevelController.h"
#import <Photos/Photos.h>
#import "GQImageVideoViewer.h"


@interface TKYAddSafetyController ()<UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (nonatomic, strong)UITableView *tabelView;

@property (nonatomic, strong)UIScrollView *scrollV;

@property (nonatomic, assign)BOOL isCamera;

@property (nonatomic, strong)TKYSafetyImageOrVideoCell *safetyImgCell;

/**标题*/
@property (nonatomic, strong)NSString *questionName;
/**问题类型*/
@property (nonatomic, strong)NSString *questionType;
/**问题等级*/
@property (nonatomic, strong)NSString *questionLevel;
/**考核分数*/
@property (nonatomic, strong)NSString *scoreStr;
/**问题描述*/
@property (nonatomic, strong)NSString *questionDescription;
/**措施要求*/
@property (nonatomic, strong)NSString *measuresRequired;
/**图片或视频*/
@property (nonatomic, strong)NSMutableArray *imageArrM;
/**限改日期 */
@property (nonatomic, strong)NSString *modificationDateStr;
/**资料关联*/
@property (nonatomic, strong)NSString *documentId;
/**分部分项*/
@property (nonatomic, strong)NSString *subdivisionId;
/**发起人*/
@property (nonatomic, strong)NSString *initiator;
/**责任人*/
@property (nonatomic, strong)NSString *supervisor;
/**督办人*/
@property (nonatomic, strong)NSString *acceptor;
/**验收人*/
@property (nonatomic, strong)NSString *ccPerson;
/**状态*/
@property (nonatomic, strong)NSString *processStatus;




@end

@implementation TKYAddSafetyController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置导航
    [self setupNavigation];
    
    [self setUPUI];
}

/**
 设置导航
 */
- (void)setupNavigation{
    self.navigationItem.title = @"安全填报";
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"back_btn"]  style:UIBarButtonItemStylePlain target:self action:@selector(backButton:)];
    //设置导航栏文字颜色
    self.navigationController.navigationBar.titleTextAttributes = [NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.navigationController.navigationBar.barTintColor = KNavColor;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(sendAction:)];
}

- (void)setUPUI{
    [self.view addSubview:self.scrollV];
    [self.scrollV addSubview:self.tabelView];
}

/**
 返回按钮*/
- (void)backButton:(UIBarButtonItem *)barButtonItem{
    [self dismissViewControllerAnimated:YES completion:nil];
}

/**发送按钮*/
- (void)sendAction:(UIBarButtonItem *)barButtonItem{
    NSLog(@"%@", self.imageArrM);
    NSMutableArray *imageM = [NSMutableArray array];
    
    if (self.questionName.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请输入任务标题"];
        return;
    }
    
    if (self.questionType.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请选择问题类型"];
        return;
    }
    
    if (self.questionLevel.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请选择问题级别"];
        return;
    }
    
    if (self.scoreStr.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请填写考核分数"];
        return;
    }
    
    if (self.questionDescription.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"问题描述不能为空"];
        return;
    }
    
    if (self.questionDescription.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"措施要求不能为空"];
        return;
    }
    
    if (self.modificationDateStr.length == 0) {
        [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:@"请选择截至时间"];
        return;
    }
    NSLog(@"%@",imageM);
    NSDictionary *parameters = @{
                                 @"token":[[NSUserDefaults standardUserDefaults]objectForKey:kToken],
                                 @"safeQualityFlag":@"1",
                                 @"delFlag":@"0",
                                 @"projectId":@"",
                                 @"questionName":self.questionName,
                                 @"questionType":self.questionType,
                                 @"questionLevel":self.questionLevel,
                                 @"score":self.scoreStr,
                                 @"questionDescription":self.questionDescription,
                                 //@"fileList":imageM,
                                 @"modificationDateStr":self.modificationDateStr,
                                 @"documentId":@"",
                                 @"subdivisionId":@"",
                                 @"initiator":@"",
                                 @"liablePerson":@"",
                                 @"supervisor":@"",
                                 @"acceptor":@"",
                                 @"ccPerson":@"",
                                 @"processStatus":@"",
                                 };
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [SVProgressHUD showSVProgressHUDWithAnimationType:SVProgressHUDAnimationTypeFlat maskType:SVProgressHUDMaskTypeBlack style:SVProgressHUDStyleDark status:@"正在提交数据"];
    
    [manager POST:[NSString stringWithFormat:@"%@%@",kApiBaseUrl,KSaveQuestionUrl] parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传视频和图片
        for (NSDictionary *dic in self.imageArrM) {
            NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
            formatter.dateFormat=@"yyyyMMddHHmmss";
            NSString *str=[formatter stringFromDate:[NSDate date]];
            if ([[dic objectForKey:@"GQIsImageURL"]integerValue] == 1) {
                NSString *fileName=[NSString stringWithFormat:@"%@.jpg",str];
                UIImage *image = dic[GQURLString];
                // UIImage *compreImage = [image scaleToWidth:1024];
                NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
                [formData appendPartWithFileData:imageData name:@"uploadFileList" fileName:fileName mimeType:@"image/png"];
            }else{
                NSData *fileData = [NSData dataWithContentsOfFile:dic[GQURLString]];
                [formData appendPartWithFileData:fileData name:@"uploadFileList" fileName:[NSString stringWithFormat:@"%@.mp4",str] mimeType:@"application/octet-stream"];
            }
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject[@"code"]integerValue] == 0) {
            [SVProgressHUD dismiss];
            [self dismissViewControllerAnimated:YES completion:nil];
        }else{
            [SVProgressHUD showSVProgressImage:nil Duration:2.0 FontSize:16 status:responseObject[@"msg"]];;
        }
        NSLog(@"===%@, %@", responseObject[@"msg"],responseObject[@"code"]);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [SVProgressHUD showErrorWithStatus:@"网络错误, 请稍候再试"];
    }];
#warning 发送按钮
    NSLog(@"分数%@", self.scoreStr);
}


#pragma mark -- UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 8;
    }else if (section == 1){
        return 2;
    }else{
        return 4;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0001;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 30;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return @"基本信息";
    }else if(section == 1){
        return @"模型信息";
    }else{
        return @"相关人员";
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    TKYAddSafetyCell *cell = [tableView dequeueReusableCellWithIdentifier:kAddSafetyCellID];
    
     __weak typeof(cell) weakCell = cell;
     __weak typeof(self) weakSelf = self;
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:{
                //TKYAddSafetyCell *cell = [tableView dequeueReusableCellWithIdentifier:kAddSafetyCellID];
                cell.titleLabel.text = @"任务标题";
                cell.selectedButton.hidden = YES;
                cell.contentTF.placeholder = @"请输入标题";
                //输入标题
                cell.contentTFBlock = ^(NSString *str) {
                    NSLog(@"输入标题%@", str);
                    weakSelf.questionName = str;
                };
                
            }
                break;
            case 1:{
                cell.titleLabel.text = @"类型";
                cell.contentTF.userInteractionEnabled = NO;
                cell.selectedCellBlock = ^(UIButton *button) {
                    TKYQuestionTypeController * questionTypeVC = [[TKYQuestionTypeController alloc]init];
                    questionTypeVC.selectedQuestionTypeBlock = ^(TKYQuestionTypeModel *questionType) {
                        weakCell.contentTF.text = questionType.name;
                        weakSelf.questionType = questionType.name;
                    };
                    [self.navigationController pushViewController:questionTypeVC animated:YES];
                };
            }
                break;
            case 2:{
                cell.titleLabel.text = @"问题级别";
                cell.contentTF.userInteractionEnabled = NO;
                cell.selectedCellBlock = ^(UIButton *button) {
                    TKYQuestionLevelController *questionLevelVC = [TKYQuestionLevelController new];
                    questionLevelVC.selectedQuestionLevelBlock = ^(TKYQuestionLevelModel *questionLevel) {
                        weakCell.contentTF.text = questionLevel.name;
                        weakSelf.questionLevel = questionLevel.name;
                    };
                    [self.navigationController pushViewController:questionLevelVC animated:YES];
                };
            }
                break;
            case 3:{
                cell.titleLabel.text = @"考核分数";
                cell.selectedButton.hidden = YES;
                cell.contentTF.placeholder = @"请输入分数1-10";
                cell.contentTF.keyboardType = UIKeyboardTypeNumberPad;
                //输入分数
                cell.contentTFBlock = ^(NSString *str) {
                    NSLog(@"分数%@", str);
                    weakSelf.scoreStr = str;
                };
                }
                break;
            case 4:{
                TKYSafetyDescribeCell *safetyDesCell = [tableView dequeueReusableCellWithIdentifier:kSafetyDescribeCellID];
                safetyDesCell.titleLabel.text = @"问题描述";
                safetyDesCell.placeholderLabel.text = @"请输入问题描述";
                //问题描述
                safetyDesCell.describeTextBlock = ^(NSString *describeText) {
                    
                    NSLog(@"问题描述%@",describeText);
                    weakSelf.questionDescription = describeText;
                };
                return safetyDesCell;
                }
                break;
            case 5:{
                TKYSafetyDescribeCell *safetyDesCell = [tableView dequeueReusableCellWithIdentifier:kSafetyDescribeCellID];
                safetyDesCell.titleLabel.text = @"措施要求";
                safetyDesCell.placeholderLabel.text = @"请输入措施要求";
                //施工要求
                safetyDesCell.describeTextBlock = ^(NSString *describeText) {
                    
                    NSLog(@"措施要求%@",describeText);
                    weakSelf.measuresRequired = describeText;
                };
                return safetyDesCell;
                }
                break;
            case 6:{
                self.safetyImgCell = [tableView dequeueReusableCellWithIdentifier:kSafetyImageOrVideoCellID];
                //添加照片
                self.safetyImgCell.addCameraBlock = ^(UIButton *button) {
                    
                    [weakSelf addImage:button];
                    
                };
                
                self.safetyImgCell.seletetedCollectionCellBlock = ^(NSIndexPath *indexPath) {
                    
                                   // 基本调用
                                            [[GQImageVideoViewer sharedInstance] setDataArray:weakSelf.imageArrM];
                                            //    [GQImageVideoViewer sharedInstance].usePageControl = YES;
                                            [GQImageVideoViewer sharedInstance].selectIndex = 0;
                                            [GQImageVideoViewer sharedInstance].achieveSelectIndex = ^(NSInteger selectIndex){
                                                NSLog(@"%ld",selectIndex);
                                            };
                                            [GQImageVideoViewer sharedInstance].laucnDirection = GQLaunchDirectionRight;
                                            [[GQImageVideoViewer sharedInstance] showInView:weakSelf.view];
                    

                };
                
                return  self.safetyImgCell;
            }
                break;
            case 7:{
                cell.titleLabel.text = @"截至日期";
                cell.selectedCellBlock = ^(UIButton *button) {
                    
                    [BRDatePickerView showDatePickerWithTitle:@"请选择检验日期" dateType:BRDatePickerModeYMD defaultSelValue:@"" resultBlock:^(NSString *selectValue) {
                        weakCell.contentTF.text = selectValue;
                        weakSelf.modificationDateStr = selectValue;
                    }];
                };
            }
                break;
                
            default:
                break;
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            TKYSafetyMaterialCell *materialCell = [tableView dequeueReusableCellWithIdentifier:kSafetyMaterialCellID];
            
            __weak typeof(materialCell) weakMaterialCell = materialCell;
            materialCell.deleteButton.hidden = YES;
            //选择关联资料按钮
            materialCell.seletetedButtonBlock = ^(UIButton *button) {
                TKYSelectedFileController *selectedFileVC = [[TKYSelectedFileController alloc]init];
                
                selectedFileVC.returnValueBlock = ^(NSString *strValue) {
                    if (strValue.length > 0) {
                        weakMaterialCell.deleteButton.hidden = NO;
                        [weakMaterialCell.contentLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
                            //make.left.equalTo(self.contentView).with.offset(20);
                            make.top.equalTo(weakMaterialCell.titleLabel.mas_bottom).with.offset(2);
                            make.left.equalTo(weakMaterialCell.contentView).with.offset(20);
                            make.bottom.equalTo(weakMaterialCell.contentView.mas_bottom).with.offset(-2);
                            make.height.mas_equalTo(40);
                            make.width.mas_equalTo(200);

                        }];
                        [weakMaterialCell.deleteButton mas_makeConstraints:^(MASConstraintMaker *make) {
                        //make.left.equalTo(self.contentView).with.offset(20);
                          make.top.equalTo(weakMaterialCell.selectedBtn.mas_bottom).with.offset(2);
                            make.right.equalTo(weakMaterialCell.contentView).with.offset(-20);
                          make.bottom.equalTo(weakMaterialCell.contentView.mas_bottom).with.offset(-2);
                
                            make.height.mas_equalTo(20);
                            make.width.mas_equalTo(40);
                        }];
                        

//                        weakMaterialCell.deleteButton.hidden = NO;
                        weakMaterialCell.contentLabel.text = strValue;

                        [weakMaterialCell.selectedBtn setTitle:@"已关联模型" forState:UIControlStateNormal];
                    }
                    //一个cell刷新
//                    NSIndexPath *indexPathA = [NSIndexPath indexPathForRow:0 inSection:1]; //刷新第0段第2行
//                    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPathA,nil] withRowAnimation:UITableViewRowAnimationNone];

                };
                [self.navigationController pushViewController:selectedFileVC animated:YES];
                
            };
            
            
            materialCell.deleteButtonBlock = ^(UIButton *button) {
                
                weakMaterialCell.contentLabel.text = @"";
                button.hidden = YES;
                [weakMaterialCell.selectedBtn setTitle:@"请关联模型" forState:UIControlStateNormal];
            };
            //[self.tabelView reloadData];
            return materialCell;
        }else{
            cell.titleLabel.text = @"分部分项";
            cell.contentTF.userInteractionEnabled = NO;
            __weak typeof(cell) weakCell = cell;
           //选择分部分项
            cell.selectedCellBlock = ^(UIButton *button) {
                TKYFindTreeController *findTreeVC = [TKYFindTreeController new];
                findTreeVC.selectedBlock = ^(TKYFindTreeModel *findTreeModel) {
                    weakCell.contentTF.text = findTreeModel.name;
                    weakSelf.subdivisionId = findTreeModel.ids;
                };
                [self.navigationController pushViewController:findTreeVC animated:YES];
            };
        }
       
    }else{
        if (indexPath.row == 0) {
            cell.titleLabel.text = @"责任人";
            cell.contentTF.userInteractionEnabled = NO;
            __weak typeof(self) weakSelf = self;

            cell.selectedCellBlock = ^(UIButton *button) {
                TKYSelectedPersonController *selectedVC = [TKYSelectedPersonController new];
                selectedVC.selectedMemberBlock = ^(NSArray *memberS) {
                    weakCell.contentTF.text = [weakSelf setPerson:memberS];
                };

                [weakSelf.navigationController pushViewController:selectedVC animated:YES];
            };
        }else if (indexPath.row == 1){
            cell.titleLabel.text = @"督办人";
            cell.contentTF.userInteractionEnabled = NO;
            __weak typeof(self) weakSelf = self;
            cell.selectedCellBlock = ^(UIButton *button) {
                TKYSelectedPersonController *selectedVC = [TKYSelectedPersonController new];
                selectedVC.selectedMemberBlock = ^(NSArray *memberS) {
                    weakCell.contentTF.text = [weakSelf setPerson:memberS];
                };
                [weakSelf.navigationController pushViewController:selectedVC animated:YES];
            };

        }else if (indexPath.row == 2){
            cell.titleLabel.text = @"验收人";
            cell.contentTF.userInteractionEnabled = NO;
            __weak typeof(self) weakSelf = self;
            //选择验收人
            cell.selectedCellBlock = ^(UIButton *button) {
                TKYSelectedPersonController *selectedVC = [TKYSelectedPersonController new];
                selectedVC.selectedMemberBlock = ^(NSArray *memberS) {
                    weakCell.contentTF.text = [weakSelf setPerson:memberS];
                };
                
                [weakSelf.navigationController pushViewController:selectedVC animated:YES];
            };

        }else{
            cell.titleLabel.text = @"抄送人";
            cell.contentTF.userInteractionEnabled = NO;
            __weak typeof(self) weakSelf = self;
             //选择抄送人
            cell.selectedCellBlock = ^(UIButton *button) {
                TKYSelectedPersonController *selectedVC = [TKYSelectedPersonController new];
                selectedVC.selectedMemberBlock = ^(NSArray *memberS) {
                    weakCell.contentTF.text = [weakSelf setPerson:memberS];
                };
                [weakSelf.navigationController pushViewController:selectedVC animated:YES];
            };
        }
    }
    return cell;
}

#pragma mark--添加图片
- (void)addImage:(UIButton *)button{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"相册选择照片" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self photoLibraryImage];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.isCamera = YES;
        [self phonCameraImage];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"相机选择视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self choosevideo];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"录制视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.isCamera = YES;
        [self startvideo];
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
    
    
}

//拍摄照片
- (void)phonCameraImage{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    //NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
    // NSLog(@"%@",availableMedia);
    //Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    //ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[0]];//设置媒体类型为public.movie
    [self presentViewController:ipc animated:YES completion:nil];
    ipc.delegate = self;//设置委托
    
}

//选择相册图片
- (void)photoLibraryImage{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    // NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
    //NSLog(@"%@",availableMedia);
    //Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    // ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[0]];//设置媒体类型为public.movie
    [self presentViewController:ipc animated:YES completion:nil];
    ipc.delegate = self;//设置委托
    
}

//选择本地视频
- (void)choosevideo
{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
    [self presentViewController:ipc animated:YES completion:nil];
    ipc.delegate = self;//设置委托
    
}

//录制视频
- (void)startvideo
{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;//sourcetype有三种分别是camera，photoLibrary和photoAlbum
    NSArray *availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];//Camera所支持的Media格式都有哪些,共有两个分别是@"public.image",@"public.movie"
    ipc.mediaTypes = [NSArray arrayWithObject:availableMedia[1]];//设置媒体类型为public.movie
    [self presentViewController:ipc animated:YES completion:nil];
    ipc.videoMaximumDuration = 10.0f;//30秒
    ipc.delegate = self;//设置委托
    
}

- (CGFloat)getFileSize:(NSString *)path
{
    NSLog(@"%@",path);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float filesize = -1.0;
    if ([fileManager fileExistsAtPath:path]) {
        NSDictionary *fileDic = [fileManager attributesOfItemAtPath:path error:nil];//获取文件的属性
        unsigned long long size = [[fileDic objectForKey:NSFileSize] longLongValue];
        filesize = 1.0*size/1024;
    }else{
        NSLog(@"找不到文件");
    }
    return filesize;
}

//此方法可以获取文件的大小，返回的是单位是KB。
- (CGFloat) getVideoLength:(NSURL *)URL
{
    AVURLAsset *avUrl = [AVURLAsset assetWithURL:URL];
    CMTime time = [avUrl duration];
    int second = ceil(time.value/time.timescale);
    return second;
}//此方法可以获取视频文件的时长。

//完成视频录制，并压缩后显示大小、时长
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image;
    NSString *key;
    NSDictionary *dict;
    image = [info objectForKey:UIImagePickerControllerOriginalImage];
    key = [NSString stringWithFormat:@"%p%@",image,@"NO"];
    if (image) {
        dict = @{
                 GQIsImageURL:@(YES),
                 GQURLString:image,
                 @"image":image
                 };
    }
    
    //UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    NSURL *sourceURL = [info objectForKey:UIImagePickerControllerMediaURL];
    NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:sourceURL]]);
    NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[sourceURL path]]]);
    NSURL *newVideoUrl ; //一般.mp4
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];//用时间给文件全名，以免重复，在测试的时候其实可以判断文件是否存在若存在，则删除，重新生成文件即可
    [formater setDateFormat:@"yyyy-MM-dd-HH:mm:ss"];
    newVideoUrl = [NSURL fileURLWithPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/output-%@.mp4", [formater stringFromDate:[NSDate date]]]] ;//这个是保存在app自己的沙盒路径里，后面可以选择是否在上传后删除掉。我建议删除掉，免得占空间。
    //获取第一帧的图片
    if (sourceURL) {
        image = [self firstFrameWithVideoURL:sourceURL size:CGSizeMake(100, 100)];
        key = [NSString stringWithFormat:@"%p%@",image,@"YES"];
        dict = @{
                 GQIsImageURL:@(NO),
                 GQURLString:newVideoUrl,
                 @"image":image
                 };
    }
    
    [self.imageArrM addObject:dict];
    self.safetyImgCell.imageArr = self.imageArrM;
    [self.safetyImgCell.collectionView reloadData];
    [picker dismissViewControllerAnimated:YES completion:nil];
    [self convertVideoQuailtyWithInputURL:sourceURL outputURL:newVideoUrl completeHandler:nil];
}

//压缩视频
- (void)convertVideoQuailtyWithInputURL:(NSURL*)inputURL
                              outputURL:(NSURL*)outputURL
                        completeHandler:(void (^)(AVAssetExportSession*))handler
{
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:inputURL options:nil];
    
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:avAsset presetName:AVAssetExportPresetMediumQuality];
    //  NSLog(resultPath);
    exportSession.outputURL = outputURL;
    exportSession.outputFileType = AVFileTypeMPEG4;
    exportSession.shouldOptimizeForNetworkUse= YES;
    [exportSession exportAsynchronouslyWithCompletionHandler:^(void)
     {
         switch (exportSession.status) {
             case AVAssetExportSessionStatusCancelled:
                 NSLog(@"AVAssetExportSessionStatusCancelled");
                 break;
             case AVAssetExportSessionStatusUnknown:
                 NSLog(@"AVAssetExportSessionStatusUnknown");
                 break;
             case AVAssetExportSessionStatusWaiting:
                 NSLog(@"AVAssetExportSessionStatusWaiting");
                 break;
             case AVAssetExportSessionStatusExporting:
                 NSLog(@"AVAssetExportSessionStatusExporting");
                 break;
             case AVAssetExportSessionStatusCompleted:
                 NSLog(@"AVAssetExportSessionStatusCompleted");
                 NSLog(@"%@",[NSString stringWithFormat:@"%f s", [self getVideoLength:outputURL]]);
                 NSLog(@"%@", [NSString stringWithFormat:@"%.2f kb", [self getFileSize:[outputURL path]]]);
                 
                 //UISaveVideoAtPathToSavedPhotosAlbum([outputURL path], self, nil, NULL);//这个是保存到手机相册
                // [self alertUploadVideo:outputURL];
                 break;
             case AVAssetExportSessionStatusFailed:
                 NSLog(@"AVAssetExportSessionStatusFailed");
                 break;
         }
     }];
}

//是否上传视频
-(void)alertUploadVideo:(NSURL*)URL{
    CGFloat size = [self getFileSize:[URL path]];
    NSString *message;
    NSString *sizeString;
    CGFloat sizemb= size/1024;
    if(size<=1024){
        sizeString = [NSString stringWithFormat:@"%.2fKB",size];
    }else{
        sizeString = [NSString stringWithFormat:@"%.2fMB",sizemb];
    }
    
    
    if(sizemb<2){
        [self uploadVideo:URL];
    }
    
    else if(sizemb<=5){
        message = [NSString stringWithFormat:@"视频%@，大于2MB会有点慢，确定上传吗？", sizeString];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil
                                                                                  message: message
                                                                           preferredStyle:UIAlertControllerStyleAlert];
        
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
            [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间（沙盒）
            
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [self uploadVideo:URL];
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
        
        
    }else if(sizemb>5){
        message = [NSString stringWithFormat:@"视频%@，超过5MB，不能上传，抱歉。", sizeString];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle: nil message: message preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshwebpages" object:nil userInfo:nil];
            [[NSFileManager defaultManager] removeItemAtPath:[URL path] error:nil];//取消之后就删除，以免占用手机硬盘空间
            
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

/**
 上传视频
 */
-(void)uploadVideo:(NSURL*)URL{
    
}

#pragma mark ---- 获取图片第一帧
- (UIImage *)firstFrameWithVideoURL:(NSURL *)url size:(CGSize)size
{
    // 获取视频第一帧
    NSDictionary *opts = [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:NO] forKey:AVURLAssetPreferPreciseDurationAndTimingKey];
    AVURLAsset *urlAsset = [AVURLAsset URLAssetWithURL:url options:opts];
    AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:urlAsset];
    generator.appliesPreferredTrackTransform = YES;
    generator.maximumSize = CGSizeMake(size.width, size.height);
    NSError *error = nil;
    CGImageRef img = [generator copyCGImageAtTime:CMTimeMake(0, 10) actualTime:NULL error:&error];
    {
        return [UIImage imageWithCGImage:img];
    }
    return nil;
}

#pragma mark-- 懒加载
- (NSMutableArray *)imageArrM{
    if (!_imageArrM) {
        _imageArrM = [NSMutableArray array];
    }
    return _imageArrM;
}

#pragma mark-- 懒加载
- (UITableView *)tabelView{
    if (_tabelView == nil) {
        _tabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight+kHeightScale *400 ) style:UITableViewStyleGrouped];
        _tabelView.delegate = self;
        _tabelView.dataSource = self;
//        _tabelView.scrollEnabled = NO;
        //_tabelView.estimatedRowHeight = 500;  //  随便设个不那么离谱的值
        //_tabelView.rowHeight = UITableViewAutomaticDimension;
        [_tabelView registerNib:[UINib nibWithNibName:@"TKYAddSafetyCell" bundle:nil] forCellReuseIdentifier:kAddSafetyCellID];
        [_tabelView registerClass:[TKYSafetyDescribeCell class] forCellReuseIdentifier:kSafetyDescribeCellID];
        [_tabelView registerClass:[TKYSafetyImageOrVideoCell class] forCellReuseIdentifier:kSafetyImageOrVideoCellID];
        [_tabelView registerClass:[TKYSafetyMaterialCell class] forCellReuseIdentifier:kSafetyMaterialCellID];

    }
    return _tabelView;
}

//- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
//{
//    UIView *view = touch.view;
//    if ([view isKindOfClass:[UITableView class]] || [@"UITableViewCellContentView" isEqualToString:[[view class] description]] )
//    {
//        return NO;
//    }
//
//    return YES;
//}

- (UIScrollView *)scrollV {
    if (_scrollV == nil) {
       // self.automaticallyAdjustsScrollViewInsets = NO;
        _scrollV = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        _scrollV.scrollEnabled = YES;
        //_scrollV.pagingEnabled = YES;
        _scrollV.showsHorizontalScrollIndicator = NO;
        _scrollV.showsVerticalScrollIndicator = YES;
       // _scrollV.backgroundColor = [UIColor redColor];
        _scrollV.contentSize = CGSizeMake(0, kScreenHeight *2);
    }
    return _scrollV;
}

- (NSString *)setPerson:(NSArray *)arr{
    NSMutableString *strM = [NSMutableString string];
    for (NSString *personStr in arr) {
        [strM appendString:[NSString stringWithFormat:@"%@,",personStr]];
    }
    return strM.copy;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
